import 'package:flame/components.dart';
import 'package:flame_audio/flame_audio.dart';

const double birdSize = 48;
const double maxMoveYAxisBeforeGame = 20;

class BirdComponent extends SpriteAnimationComponent {
  static int statusBeforeGame = 0x00;
  static int statusFlying = 0x01;
  static int statusGameOver = 0x02;

  BirdComponent(this.screenSize, [this.onStatusChangedCallback])
      : super(size: Vector2(birdSize, birdSize), anchor: Anchor.center);

  Vector2 screenSize;
  Function? onStatusChangedCallback;

  double currentMoveYAxisBeforeGame = 0;
  bool moveDirectionUp = true;
  int currentStatus = statusBeforeGame;
  double axisYSpeed = 0.5;

  @override
  Future<void> onLoad() async {
    List<Sprite> sprites = [];
    if (currentStatus == statusBeforeGame) {
      sprites.add(await Sprite.load('bird0_1.png'));
    }
    animation = SpriteAnimation.spriteList(sprites, stepTime: 0.1);
  }

  @override
  void onGameResize(Vector2 size) {
    super.onGameResize(size);
    screenSize = size;
    position = Vector2(size.x / 2, (size.y - 96) / 2);
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (currentStatus == statusBeforeGame) {
      _moveUpAndDown();
    } else if (currentStatus == statusFlying) {
      _freeFly();
    }
  }

  // 上下移动（仅在游戏前调用）
  void _moveUpAndDown() {
    if (moveDirectionUp) {
      position.sub(Vector2(0, 0.5));
    } else {
      position.add(Vector2(0, 0.5));
    }
    currentMoveYAxisBeforeGame++;
    if (currentMoveYAxisBeforeGame >= maxMoveYAxisBeforeGame) {
      moveDirectionUp = !moveDirectionUp;
      currentMoveYAxisBeforeGame = 0;
    }
  }

  // 自由飞翔（自由落体，仅在游戏时调用）
  void _freeFly() {
    // 落地游戏结束
    if (position.y >= screenSize.y - 96 - 12) {
      changeStatus(statusGameOver);
      position.y = screenSize.y - 96 - 12;
      // 到达屏幕顶端，限制小鸟在屏幕内
    } else if (position.y <= 0 + 12) {
      position.y = 13;
      axisYSpeed = 0;
    } else {
      // 其它情况均加速落地
      position.add(Vector2(0, axisYSpeed));
      axisYSpeed += 0.3;
    }
  }

  // 改变状态
  void changeStatus(int status) async {
    if (status != currentStatus) {
      currentStatus = status;
      List<Sprite> sprites = [];
      if (currentStatus == statusFlying) {
        playAudioFlying();
        sprites.add(await Sprite.load('bird0_0.png'));
        sprites.add(await Sprite.load('bird0_1.png'));
        sprites.add(await Sprite.load('bird0_2.png'));
      } else if (currentStatus == statusBeforeGame) {
        if (FlameAudio.bgm.isPlaying) {
          FlameAudio.bgm.stop();
        }
        sprites.add(await Sprite.load('bird0_1.png'));
      } else {
        playAudioHit();
        sprites.add(await Sprite.load('bird0_1.png'));
      }
      animation = SpriteAnimation.spriteList(sprites, stepTime: 0.1);
      if (onStatusChangedCallback != null) {
        onStatusChangedCallback!(currentStatus);
      }
    }
  }

  // 播放游戏中背景音乐
  void playAudioFlying() {
    if (FlameAudio.bgm.isPlaying) {
      FlameAudio.bgm.stop();
    }
    FlameAudio.bgm.initialize();
    FlameAudio.bgm.play("flying.mp3");
  }

  // 播放撞击声
  void playAudioHit() {
    if (FlameAudio.bgm.isPlaying) {
      FlameAudio.bgm.stop();
    }
    FlameAudio.play("hit.mp3");
  }

  // 向上飞（仅在游戏时调用）
  void flyUp() {
    // 改变纵向加速度
    if (currentStatus == statusFlying) {
      axisYSpeed -= 5;
    }
  }

  // 重置状态
  void reset() {
    currentStatus = statusBeforeGame;
    position = screenSize / 2;
    axisYSpeed = 0;
  }

  // 获取当前状态
  int getCurrentStatus() {
    return currentStatus;
  }

  // 获取当前坐标
  Vector2 getCurrentPosition() {
    return position;
  }
}
